package com.dc.bobaoge.project.v2.to.v3.business.core.method.user;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dc.bobaoge.base.entity.core.po.SystemUserExtraInfo;
import com.dc.bobaoge.base.mapper.core.SystemUserExtraInfoMapper;
import com.dc.bobaoge.project.base.core.old.entity.OldCoreUser;
import com.dc.bobaoge.project.base.core.old.mapper.OldCoreUserMapper;
import com.own.business.sync.trigger.base.entity.SyncTrigger;
import com.own.business.sync.trigger.base.method.ResolveMethod;
import com.own.business.system.user.mapper.SystemUserMapper;
import com.own.component.common.exception.BusinessSimpleException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * UserUpdateExtraInfoResolveMethod
 *
 * @author chenxueli
 * @date 2024-01-16 14:26:00
 */
@Slf4j
@Component
public class UserUpdateExtraInfoResolveMethod implements ResolveMethod {

    @Resource
    private OldCoreUserMapper oldCoreUserMapper;

    @Resource
    private SystemUserMapper systemUserMapper;
    @Resource
    private SystemUserExtraInfoMapper systemUserExtraInfoMapper;

    /**
     * 修改的处理方法
     *
     * @param trigger 日志信息
     */
    @Override
    public void update(SyncTrigger trigger) {
        // 查询用户信息是否存在
        var oldCoreUser = oldCoreUserMapper.selectById(trigger.getTargetId());
        if (oldCoreUser == null) {
            throw new BusinessSimpleException("用户信息不存在");
        }
        // 查询是否已经存在当前用户了
        var systemUser = systemUserMapper.selectById(oldCoreUser.getUserId());
        if (systemUser == null) {
            throw new BusinessSimpleException("用户信息不存在");
        }
        // 查询原来的额外信息
        var wrapper = new LambdaUpdateWrapper<SystemUserExtraInfo>().eq(SystemUserExtraInfo::getFkUserId, systemUser.getId());
        var extraInfo = systemUserExtraInfoMapper.selectOne(wrapper);
        if (extraInfo == null) {
            extraInfo = buildCommonUserExtraInfo(new SystemUserExtraInfo(), oldCoreUser);
            systemUserExtraInfoMapper.insert(extraInfo);
        } else {
            buildCommonUserExtraInfo(extraInfo, oldCoreUser);
            systemUserExtraInfoMapper.updateById(extraInfo);
        }
    }

    /**
     * 创建额外的用户信息
     *
     * @param extraInfo   额外的用户信息
     * @param oldCoreUser 旧数据库用户数据
     * @return 额外的用户信息
     */
    public SystemUserExtraInfo buildCommonUserExtraInfo(SystemUserExtraInfo extraInfo, OldCoreUser oldCoreUser) {
        extraInfo.setFkUserId(oldCoreUser.getUserId());
        extraInfo.setQq(oldCoreUser.getUserQq());
        extraInfo.setWechat(oldCoreUser.getUserWeixin());
        return extraInfo;
    }

    /**
     * 名称信息
     *
     * @return 名称
     */
    @Override
    public String name() {
        return "user_extra_info";
    }

}
